﻿
namespace HSS.Xaml.UI.Controls
{
	#region Using Directives
	using System;
	using System.Collections;
	using System.Windows;
	using System.Collections.Generic;


	#endregion

	#region StringCollectionEditorDialog
	/// <summary>
	/// StringCollectionEditorDialog
	/// </summary>
	public partial class StringCollectionEditorDialog : ICancellableEditorDialog
	{
		#region Fields
		PropertyGridEntry _propertyGridEntry;
		IList originalTarget;
		bool isNew;
		#endregion

		#region Constructors
		/// <summary>
		/// Constructor
		/// </summary>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
		public StringCollectionEditorDialog()
		{
			if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
				throw new Exception();
			InitializeComponent();
		}
		/// <summary>
		/// Constructor
		/// </summary>
		public StringCollectionEditorDialog(PropertyGridEntry propertyGridEntry)
		{
			InitializeComponent();

			this._propertyGridEntry = propertyGridEntry;
			this.Title = "Edit - " + propertyGridEntry.Name;
			if (null == propertyGridEntry.CurrentValue)
			{
				isNew = true;
				this.originalTarget = Activator.CreateInstance(propertyGridEntry.Descriptor.PropertyType) as IList;
			}
			else
			{
				this.originalTarget = propertyGridEntry.CurrentValue as IList;
			}

			foreach (string item in this.originalTarget)
				txtStrings.Text += item + Environment.NewLine;
			txtStrings.Text = txtStrings.Text.TrimEnd(Environment.NewLine.ToCharArray());
		}
		#endregion

		#region Methods
		/// <summary>
		/// Ends the current edit operation.
		/// </summary>		
		public void EndEdit()
		{
			if (!isNew)
			{
				this.originalTarget.Clear();
				var lines = this.txtStrings.Text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
				foreach (var line in lines)
					this.originalTarget.Add(line);
			}
			else
			{
				var lines = this.txtStrings.Text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
				foreach (var line in lines)
					this.originalTarget.Add(line);
				this._propertyGridEntry.SetPropertyValue(this.originalTarget);
			}
		}
		#endregion

		#region Event Handlers
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
		private void btnOK_Click(object sender, RoutedEventArgs e)
		{
			this.DialogResult = true;
		}
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
		private void btnCancel_Click(object sender, RoutedEventArgs e)
		{
			this.DialogResult = false;
		}
		#endregion
	}
	#endregion
}